//
//  FloatBtnView.m
//  KidReading
//
//  Created by telen on 14/12/31.
//  Copyright (c) 2014年 刘赞黄Telen. All rights reserved.
//

#import "FloatBtnView.h"
#import "ConstDefine.h"

#define __DefaultBtnWH_  50
#define __DefaultBtnPod_  (5/self.ratio_w)

#define __FollowTime_ 0.08f

@implementation UIView (FloatBtnView)

ASSOCIATED(fbv_followView, setFbv_followView, UIView*, OBJC_ASSOCIATION_ASSIGN);
ASSOCIATED(fbv_followOffsetValue, setFbv_followOffsetValue, NSValue*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(fbv_bool_KeepSizeValue, setFbv_bool_KeepSizeValue, NSNumber*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED_float(fbv_followPodValue, setFbv_followPodValue);

- (CGPoint)fbv_followOffset
{
    return [self.fbv_followOffsetValue CGPointValue];
}
- (BOOL)fbv_keepSize
{
    return [self.fbv_bool_KeepSizeValue boolValue];
}
@end

@implementation FloatBtnView

- (void)dealloc
{
#if __Debug_is_dealloced_log
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
#endif
}

+ (FloatBtnView *)floatBtnsWtihSuperView:(UIView *)superView
{
    FloatBtnView* view = [[FloatBtnView alloc] initWithFrame:CGRectZero andSuperV:superView];
    return view;
}

- (instancetype)initWithFrame:(CGRect)frame andSuperV:(UIView*)sv
{
    if (self = [super initWithFrame:frame]) {
        _superV = sv;
    }
    return self;
}

- (void)setHomeBtn:(StatusButton_2_View*)btn andOtherFloatViews:(NSArray *)views
{
    homeBtn = btn;
    viewsArr = views;
}

- (void)doneSetting
{
    if (!homeBtn){
        return;
    }
    if (CGRectEqualToRect(self.canBerthRect, CGRectZero)) {
        self.canBerthRect = self.superV.bounds;
    }
    if (CGSizeEqualToSize(self.allBtnSize, CGSizeZero)) {
        self.allBtnSize = CGSizeMake(__DefaultBtnWH_, __DefaultBtnWH_);
    }
    //
    CGFloat b_w = self.allBtnSize.width;
    CGFloat b_h = self.allBtnSize.height;
    CGFloat can_w = self.canBerthRect.size.width;
    CGFloat can_x = self.canBerthRect.origin.x;
    CGRect frame = CGRectMake(0, 0, b_w,b_h);
    CGPoint pt = CGPointMake(can_x+can_w-b_w/2-__DefaultBtnPod_, -b_h*2);
//    CGFloat can_h = self.canBerthRect.size.height;
//    CGRect frame = CGRectMake(0, 0, b_w,b_h);
//    CGPoint pt = CGPointMake(can_w-b_w/2-__DefaultBtnPod_, can_h/2-b_h/2-__DefaultBtnPod_*10);

    //
    for (int i = (int)viewsArr.count-1; i >= 0; i--) {
        UIView* subview = [viewsArr objectAtIndex:i];
        if(!subview.fbv_keepSize)subview.frame = frame;
        CGPoint ptc = pt;
        ptc.y -= (b_h+__DefaultBtnPod_)*(i+1);
        subview.center = ptc;
        [self.superV addSubview:subview];
    }
    //
    homeBtn.frame = frame;
    homeBtn.center = pt;
    homeBtn.delegate = self;
    [self.superV addSubview:homeBtn];
    //
    //创建手势
    UIPanGestureRecognizer *panGR =
    [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didDragged:)];
    //限定操作的触点数
    [panGR setMaximumNumberOfTouches:1];
    [panGR setMinimumNumberOfTouches:1];
    //将手势添加到draggableObj里
    [homeBtn addGestureRecognizer:panGR];
    //初始修整x
    CGPoint edpt = [self getEdgeBerthPoint];
    pt.x = edpt.x;
    pt.y = edpt.y-b_h*3;
    homeBtn.center = pt;
    homeBtn.hidden = YES;
}

- (void)layoutDoneSetting
{
    homeBtn.hidden = NO;
    [self edgeBerth];
}

- (void)reLayLoutFloatViews:(NSArray *)views
{
    NSMutableArray* oldViews = [NSMutableArray arrayWithArray:viewsArr];
    CGPoint pt = homeBtn.center;
    CGFloat b_w = self.allBtnSize.width;
    CGFloat b_h = self.allBtnSize.height;
    CGRect frame = CGRectMake(0, 0, b_w,b_h);
    for (UIView* subview in views) {
        BOOL theSame = NO;
        for (UIView* vw in oldViews) {
            if (subview == vw) {
                theSame = YES;
                [oldViews removeObject:vw];
                break;
            }
        }
        if (!theSame) {
            if(!subview.fbv_keepSize)subview.frame = frame;
            subview.center = pt;
            [self.superV addSubview:subview];
        }
    }
    for (UIView* view in oldViews) {
        [view removeFromSuperview];
    }
    //
    viewsArr = views;
    for (NSInteger i = viewsArr.count-1; i >= 0; i--) {
        UIView* view = [viewsArr objectAtIndex:i];
        [self.superV insertSubview:view belowSubview:homeBtn];
    }
    //
    if (viewsArr.count >0) {
        homeBtn.hidden = NO;
        if(homeBtn.onOff){
            [self followPosition:homeBtn.center index:0];
        }else{
            [self hidePosition:homeBtn.center index:0];
        }
    }else{
        homeBtn.hidden = YES;
    }
    [self edgeBerth];
}

- (void)didDragged:(UIPanGestureRecognizer*)sender
{
    if (sender.state == UIGestureRecognizerStateChanged ||
        sender.state == UIGestureRecognizerStateEnded) {
        //注意，这里取得的参照坐标系是该对象的上层View的坐标。
        CGPoint offset = [sender translationInView:self.superV];
        UIView *draggableObj = homeBtn;
        //通过计算偏移量来设定draggableObj的新坐标
        CGPoint pt = CGPointMake(draggableObj.center.x + offset.x, draggableObj.center.y + offset.y);
        [draggableObj setCenter:pt];
        //初始化sender中的坐标位置。如果不初始化，移动坐标会一直积累起来。
        [sender setTranslation:CGPointMake(0, 0) inView:self.superV];
        //
        if (sender.state == UIGestureRecognizerStateEnded) {
            [self edgeBerth];
            //telen 统计
            //[UMSAgent postEvent:@"Toolbar_drag" label:self.bookName];
            //[NSObject msgToClassName:@"UMSAgent" menthed:@"postEvent:label:" refs:@[@"Toolbar_drag",self.bookName] needReturnValue:NO];
        }else{
            if(homeBtn.onOff){
                [self followPosition:homeBtn.center index:0];
            }else{
                [self hidePosition:homeBtn.center index:0];
            }
        }
    }
}

- (void)followPosition:(CGPoint)pt index:(NSInteger)i
{
    [self followPosition:pt index:i time:__FollowTime_ sepFollowCount:0];
}

- (void)followPosition:(CGPoint)pt index:(NSInteger)i time:(CGFloat)durtime sepFollowCount:(NSInteger)scout
{
    if (i < viewsArr.count) {
        UIView* view = [viewsArr objectAtIndex:i];
        //核心，位置计算
        CGFloat b_h = self.allBtnSize.height;
        CGFloat b_w = self.allBtnSize.width;
        CGPoint ptc = pt;
        ptc.y -= (b_h+__DefaultBtnPod_)*(i-scout+1)*(_horizontal ? 0 : 1);
        ptc.x -= (b_w+__DefaultBtnPod_)*(i-scout+1)*(_horizontal ? 1 : 0);
        if (view.fbv_followOffsetValue && view.fbv_followView) {
            CGPoint offset = view.fbv_followOffset;
            ptc = view.fbv_followView.center;
            ptc.x += offset.x;
            ptc.y += offset.y;
            scout++;
        }
        //
        [UIView animateWithDuration:durtime delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            view.hidden = NO;
            view.center = ptc;
        } completion:^(BOOL finished) {
            [self followPosition:pt index:i+1 time:durtime sepFollowCount:scout];
        }];
    }
}

- (void)hideBtnList
{
    CGFloat durtime = __FollowTime_;
    CGPoint ptPod = CGPointMake(homeBtn.size.width*0.3*(_horizontal?-1:0), homeBtn.size.height*0.3*(_horizontal?0:1));
    CGPoint pt = CGPointMake(homeBtn.center.x+ptPod.x, homeBtn.center.y-ptPod.y);
    [UIView animateWithDuration:durtime delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        homeBtn.center = pt;
    } completion:^(BOOL finished) {
        [self hidePosition:homeBtn.center index:0];
    }];
}

- (void)unHideBtnList
{
    int count = (int)viewsArr.count;
    CGFloat durtime = __FollowTime_;
    [self followPosition:homeBtn.center index:0];
    CGPoint ptPod = CGPointMake(homeBtn.size.width*0.3*(_horizontal?1:0), homeBtn.size.height*0.3*(_horizontal?0:1));
    CGPoint pt = CGPointMake(homeBtn.center.x+ptPod.x, homeBtn.center.y+ptPod.y);
    [UIView animateWithDuration:durtime delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        homeBtn.center = pt;
    } completion:^(BOOL finished) {
        [self followPosition:homeBtn.center index:0];
    }];
    [self performSelector:@selector(edgeBerth) withObject:nil afterDelay:durtime*count];
}

- (void)hidePosition:(CGPoint)pt index:(NSInteger)i
{
    [self hidePosition:pt index:i time:__FollowTime_];
}

- (void)hidePosition:(CGPoint)pt index:(NSInteger)i time:(CGFloat)durtime
{
    if (i < viewsArr.count) {
        UIView* view = [viewsArr objectAtIndex:i];
        CGPoint ptc = pt;
        [UIView animateWithDuration:durtime delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            view.center = ptc;
        } completion:^(BOOL finished) {
            [self hidePosition:pt index:i+1 time:durtime];
            view.hidden = YES;
        }];
    }
}

- (void)edgeBerthToPosition:(CGPoint)pt
{
    CGFloat durtime = 0.1f;
    //
    if(homeBtn.onOff){
        [UIView animateWithDuration:durtime delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            homeBtn.center = pt;
        }completion:^(BOOL finished) {
            [self followPosition:pt index:0 time:durtime sepFollowCount:0];
        }];
    }else{
        [UIView animateWithDuration:durtime delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            homeBtn.center = pt;
        } completion:^(BOOL finished) {}];
        [self hidePosition:pt index:0];
    }
}

- (CGPoint)getEdgeBerthPoint
{
    if (self.horizontal) {
        return [self getEdgeBerthPoint_h];
    }else{
        return [self getEdgeBerthPoint_v];
    }
}

- (CGPoint)getEdgeBerthPoint_h
{
    CGFloat cx = self.canBerthRect.origin.x;
    CGFloat cy = self.canBerthRect.origin.y;
    CGFloat cw = self.canBerthRect.size.width;
    CGFloat ch = self.canBerthRect.size.height;
    //
    CGFloat w = self.allBtnSize.width;
    CGFloat h = self.allBtnSize.height;
    NSInteger count = 0;
    for (UIView* view in viewsArr) {
        if (!(view.fbv_followOffsetValue && view.fbv_followView)) {
            count++;
        }
    }
    if (homeBtn.onOff) {
        w += (w+__DefaultBtnPod_)*count;
    }
    CGPoint pt = homeBtn.center;
    if (pt.y < h+cy) pt.y = h+cx;
    if (pt.y > cy+ch-h) pt.y = cy+ch-h;
    if (pt.x < w+cx) pt.x = w+cx;
    if (pt.x > cx+cw-h) pt.x = cx+cw-h;
    //
    if (pt.y >ch/2+cy) {
        pt.y = cy+ch-h;
    }else{
        pt.y = h+cy;
    }
    return pt;
}

- (CGPoint)getEdgeBerthPoint_v
{
    CGFloat cx = self.canBerthRect.origin.x;
    CGFloat cy = self.canBerthRect.origin.y;
    CGFloat cw = self.canBerthRect.size.width;
    CGFloat ch = self.canBerthRect.size.height;
    //
    CGFloat w = self.allBtnSize.width;
    CGFloat h = self.allBtnSize.height;
    NSInteger count = 0;
    CGFloat pod = 0;
    for (UIView* view in viewsArr) {
        if (!(view.fbv_followOffsetValue && view.fbv_followView)) {
            count++;
        }else{
            pod += view.fbv_followPodValue;
        }
    }
    if (homeBtn.onOff) {
        h += (h+__DefaultBtnPod_)*count+pod;
    }
    CGPoint pt = homeBtn.center;
    if (pt.x < w+cx) pt.x = w+cx;
    if (pt.x > cx+cw-w) pt.x = cx+cw-w;
    if (pt.y < h+cy) pt.y = h+cy;
    if (pt.y > cy+ch-w) pt.y = cy+ch-w;
    //
    if (pt.x >cw/2+cx) {
        pt.x = cx+cw-w;
    }else{
        pt.x = w+cx;
    }
    return pt;
}

- (void)edgeBerth
{
    CGPoint pt = [self getEdgeBerthPoint];
    //
    [self edgeBerthToPosition:pt];
}

- (void)show
{
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        homeBtn.alpha = 1;
        for (UIView*view in viewsArr) {
            view.alpha = 1;
        }
    }completion:^(BOOL finished) {}];
}

- (void)unShow
{
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        homeBtn.alpha = 0;
        for (UIView*view in viewsArr) {
            view.alpha = 0;
        }
    }completion:^(BOOL finished) {}];
}

- (void)statusButton_2_View_didClicked:(StatusButton_2_View *)sbview
{
    if (sbview == homeBtn) {
        if(homeBtn.onOff){
            [self unHideBtnList];
        }else{
            [self hideBtnList];
        }
    }
}

@end
